/*
 * Copyright (C) 2010 M. Hautle.
 * 
 * This file is part of SimpleEL.
 * 
 * SimpleEL is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option) any later version.
 * 
 * SimpleEL is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License along with SimpleEL. If not, see <http://www.gnu.org/licenses/>.
 */
package ch.simpleel.internal;

import java.util.*;
import ch.simpleel.accessors.*;

/**
 * {@link IValueAccessor} holding an simple EL expression.
 * 
 * @param <T> The return type
 * @author M. Hautle
 */
public class ELAccessor<T> implements IValueAccessor<T> {
    /** The complete path. */
    private final String path;

    /** The el expression. */
    private final String[] elPath;

    /** Flag register for {@link #elPath} if the bit for the specified index is set then the segment represents an property name. */
    private final long properties;

    /** The type of the returned value. */
    private final Class<T> type;

    /**
     * Default constructor.
     * 
     * @param el An simple EL expression
     * @param type The type of the value returned by this expression
     * @throws IllegalArgumentException If the passed expression was illegal
     */
    public ELAccessor(String el, Class<T> type) throws IllegalArgumentException {
        ELUtils.checkEL(el);
        this.type = type;
        this.path = el;
        // current flag mask
        long bit = 1;
        // we set the first flag cause the first segment must be a property
        long properties = 1;
        final List<String> res = new ArrayList<String>(5);
        for (int p = 0, end = el.length() - 1; p < end;) {
            res.add(el.substring(p, p = ELUtils.getEndIndex(el, p)));
            // last element?
            if (p >= end)
                break;
            // compute next flag
            bit = bit << 1;
            // if the end index is a . then the next atom will be a property
            // skip following '.' (may occur after a index -> a[2].b and in this case the following element is a property)
            if (el.charAt(p) == '.' || el.charAt(++p) == '.') {
                p++;
                // store the property flag for this position
                properties |= bit;
            }
        }
        this.properties = properties;
        this.elPath = res.toArray(new String[res.size()]);
        if (elPath.length > 63)
            throw new IllegalArgumentException("This class supports a maximum of 63 elements inside the expression!");
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String getPath() {
        return path;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    @SuppressWarnings("unchecked")
    public T getValue(Object element, T fallback) throws ValueAccessException {
        try {
            // flag mask for the current index
            long mask = 1;
            int i = 0;
            for (; element != null && i < elPath.length; i++) {
                if ((properties & mask) != 0) {
                    element = ELUtils.getPropertyValue(elPath[i], element);
                } else {
                    element = ELUtils.getIndexedValue(elPath[i], element);
                    if (element == ELUtils.UNDEFINED)
                        return fallback;
                }
                mask = mask << 1;
            }
            // path not completely traversed
            if (i < elPath.length)
                return fallback;
            return (T) element;
        } catch (Exception e) {
            throw new ValueAccessException(path, e);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean setValue(Object element, T value) throws ValueAccessException {
        try {
            final int last = elPath.length - 1;
            // flag mask for the current index
            long mask = 1;
            for (int i = 0; element != null && i < last; i++) {
                if ((properties & mask) != 0) {
                    element = ELUtils.getPropertyValue(elPath[i], element);
                } else {
                    element = ELUtils.getIndexedValue(elPath[i], element);
                    if (element == ELUtils.UNDEFINED)
                        return false;
                }
                mask = mask << 1;
            }
            if (element == null)
                return false;
            return ELUtils.setValue(elPath[last], element, value);
        } catch (Exception e) {
            throw new ValueAccessException(path, e);
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Class<T> getType() {
        return type;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isReadable() {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean isWritable() {
        return true;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return getPath() + " (" + getType().getName() + ")";
    }
}
